package cn.stylefeng.guns.modular.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.guns.modular.system.controller.OrderRebateController;
import cn.stylefeng.guns.modular.system.dao.AppOrderRebateMapper;
import cn.stylefeng.guns.modular.system.dao.AppUserInfoMapper;
import cn.stylefeng.guns.modular.system.dao.ProxyUserMapper;
import cn.stylefeng.guns.modular.system.entity.AppOrderRebate;
import cn.stylefeng.guns.modular.system.service.AppOrderRebateService;
import cn.stylefeng.guns.modular.system.service.AppUserInfoService;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;

/**
 * @ClassName AppOrderRebateServiceImpl
 * @Author lzy
 * @Date 2020/1/12 5:23
 * @VERSION 1.0
 **/
@Service
public class AppOrderRebateServiceImpl extends ServiceImpl<AppOrderRebateMapper, AppOrderRebate> implements AppOrderRebateService {

    private final static Logger log = LoggerFactory.getLogger(AppOrderRebateServiceImpl.class);
    public final static BigDecimal Percent = new BigDecimal(100);

    @Autowired
    private  AppOrderRebateMapper appOrderRebateMapper;

    @Autowired
    private AppUserInfoMapper appUserInfoMapper;
    @Autowired
    private ProxyUserMapper proxyUserMapper;

    @Override
    @Transactional
    public List<Map<Object, Object>> findListByCondition(String startTime, String endTime, String orderNumber, String money,
                                                         String status, Long userId, List<String> subUserIds) {

        if(!ObjectUtils.isEmpty(orderNumber)){
            orderNumber = orderNumber + "%";
        }
        //user为登录代理id，proxyId为订单代理id
        //代表当前登录代理的代理关系
        Map<String,Object> userRelationMap = proxyUserMapper.selectRelationByPid(userId.toString());
        User user = proxyUserMapper.selectById(userId);
        int userLevel = (int) userRelationMap.get("level");//登录代理的代理等级
        BigDecimal userRate = user.getExchangeRate();//登录代理费率
        log.info("当前登录代理" + userId + "的level为：" + userLevel + "；费率：" + userRate);

        List<Map<Object, Object>> list = appOrderRebateMapper.findListByCondition(startTime, endTime, orderNumber, money, status, userId,subUserIds);
        //计算每个订单的收益
        for (Map<Object, Object> order :list) {
            BigDecimal orderProfit = null;//订单代理收益
            BigDecimal userProfit = null;//订单用户收益
            BigDecimal orderMoney = null;
            if (!ObjectUtils.isEmpty(order.get("proxyId"))
                 && !ObjectUtils.isEmpty(order.get("userId")) ){

                String userInfoId = order.get("userId").toString();//订单用户
                String proxyId = order.get("proxyId").toString();//订单用户的代理
                orderMoney = (BigDecimal)order.get("money");//订单金额
                //订单的用户收益 = 订单用户费率 * 订单金额
                BigDecimal userInfoFeiLv = appUserInfoMapper.findUserInfoFeiLv(userInfoId);//订单的用户费率
                BigDecimal divide = userInfoFeiLv.divide(Percent);
                log.info("订单的用户费率:" + divide);
                userProfit = orderMoney.multiply(divide);
                //TODO 订单用户的收益
                log.info("订单产生的用户收益为：" + userProfit);

                if (proxyId.equals(userId.toString())){
                    //代表此订单为登录代理用户的订单
                    //订单的代理收益 = (订单用户代理费率 - 订单用户费率) * 订单金额
                    BigDecimal orderProxyRate = ((BigDecimal) order.get("rate")).divide(Percent);//订单用户代理费率
                    BigDecimal minus = orderProxyRate.subtract(divide);
                    log.info("订单用户代理费率 - 订单用户费率:" + minus);
                    orderProfit = orderMoney.multiply(minus);
                    //TODO 订单代理的收益
                    log.info("订单产生的代理收益为：" + orderProfit);
                }else {
                    //代表此订单为下级代理的订单
                    //查询当前订单代理的代理关系
                    Map<String,Object> orderRelationMap = proxyUserMapper.selectRelationByPid(proxyId);
                    int orderLevel = (int) orderRelationMap.get("level");//订单代理的代理等级

                    log.info("当前"+ order.get("id").toString() +"订单的代理" + proxyId + "的level为：" + orderLevel);
                    if (orderLevel - 1 == userLevel){
                        //代表订单代理的上级就为登录代理（关系相邻）
                        //订单的收益 = （登录代理费率 - 订单代理费率）* 订单金额
                        BigDecimal orderRate = (BigDecimal) order.get("rate");//订单代理费率
                        BigDecimal minus = userRate.subtract(orderRate).divide(Percent);
                        log.info("登录代理费率 - 订单代理费率：" + minus);
                        orderProfit = orderMoney.multiply(minus);
                        log.info("订单产生的代理收益为：" + orderProfit);
                    }else {
                        //代表订单代理的上级不为登录代理（关系不相邻）
                        //获取登录代理的下一级代理并且是订单代理的上级的代理id
                        String  subPid = (String) orderRelationMap.get(ProxyUserServiceImpl.columnNamePre + (userLevel + 1));
                        System.out.println("ProxyUserServiceImpl.columnNamePre + (userLevel + 1) = " + ProxyUserServiceImpl.columnNamePre + (userLevel + 1));
                        User subUser = proxyUserMapper.selectById(subPid);
                        BigDecimal subUserRate = subUser.getExchangeRate();//登录代理下一级代理费率
                        //订单的收益 = （登录代理费率 - 登录代理下一级代理费率）* 订单金额
                        BigDecimal minus = userRate.subtract(subUserRate).divide(Percent);
                        log.info("登录代理费率 - 登录代理下一级代理费率：" + minus);
                        orderProfit = orderMoney.multiply(minus);
                        log.info("订单产生的代理收益为：" + orderProfit);
                    }
                }
                order.put("orderProfit",orderProfit);
                order.put("userProfit",userProfit);
            }else {
                order.put("userProfit",null);
                order.put("orderProfit",null);
            }
        }
        return list;
    }
}
